﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Querying;
using Medianamik.Core.Urls;
using Medianamik.Globalization;
using Medianamik.UI.Controls;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.Forum
{
    public partial class ForumList : BaseModuleListPage
    {
        #region Fields


        #endregion

        #region Events

        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
                ConfigurePage();
        }

        protected override void GridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            Grid.DataSource = new Query()
                .Where(n => n.ParentID, Comparison.Equal, ParentNodeId ?? RootNodeId)
                .Where(n => n.NodeTypeID, Comparison.Equal, GetNodeTypeId())
                .Execute();
        }

        #endregion

        #region Properties

        protected override RadGrid Grid
        {
            get { return ForumGrid; }
        }

        protected override Guid RootNodeId
        {
            get { return MedianamikModules.ForumManagement; }
        }

        protected override UpdatePanel GridUpdatePanel
        {
            get { return ForumUpdatePanel; }
        }

        protected override string ManagementURL
        {
            get { return "forummanagement.aspx"; }
        }

        protected override string ReturnUrl
        {
            get
            {
                return "";
            }
        }

        protected override void NavigateToParent(object sender, NavigateParentEventArgs e)
        {
            ParentNodeId = new Guid(e.ItemID);

            Navigate();
        }

        protected override GridActionOptions GridActionOptions
        {
            get
            {
                return GridActionOptions.All;
            }
        }

        protected override GridOptions GridOptions
        {
            get
            {
                return GridOptions.NavigateName;
            }
        }

        protected override BreadcrumbTrail BreadcrumbTrail
        {
            get { return Breadcrumbs; }
        }

        #endregion

        #region Methods

        protected override void Navigate()
        {
            base.Navigate();
            ConfigurePage();
            Grid.Rebind();
            MenuUpdatePanel.Update();
            ForumUpdatePanel.Update();
        }

        private Uri GetManagementUri()
        {
            Uri managementUrl = null;

            try
            {
                managementUrl = new Uri(ManagementURL);
            }
            catch (UriFormatException)
            {
                managementUrl = new Uri(Request.Url.ToString()
                    .Substring(0, Request.Url.ToString().LastIndexOf('/') + 1)
                    + ManagementURL.TrimStart('/'));
            }

            return managementUrl;
        }

        private void ConfigurePage()
        {
            if (ParentNode == null || ParentNode.ID == RootNodeId)
                ConfigureAddNodeButton("NewForumGroup");
            else if (ParentNode.NodeTypeID == ForumTypes.ForumGroup)
                ConfigureAddNodeButton("NewForum");
            else if (ParentNode.NodeTypeID == ForumTypes.Forum)
                ConfigureAddNodeButton("NewThread");
            else if (ParentNode.NodeTypeID == ForumTypes.ForumThread)
            {
                ConfigureAddNodeButton("NewPost");

                var nameColumn = NameColumn.ItemTemplate as GridNameColumnTemplate;
                if (nameColumn.NameButton != null)
                    nameColumn.NameButton.Enabled = false;
            }
        }

        private Guid GetNodeTypeId()
        {
            if (ParentNode == null || ParentNode.ID == RootNodeId)
                return ForumTypes.ForumGroup;

             if (ParentNode.NodeTypeID == ForumTypes.ForumGroup)
                 return ForumTypes.Forum;

           if (ParentNode.NodeTypeID == ForumTypes.Forum)
               return ForumTypes.ForumThread;

            if (ParentNode.NodeTypeID == ForumTypes.ForumThread)
                return ForumTypes.ForumPost;

            throw new ApplicationException("Unknown parent.");
        }

        private void ConfigureAddNodeButton(string translationKey)
        {
            if (ParentNode == null)
            {
                AddNodeButton.NavigateUrl = ManagementURL;
                AddNodeButton.Enabled = true;
            }
            else
            {
                if (GetForumConfigurationCount() > 0)
                {
                    var managementUrl = GetManagementUri();
                    var queryString = new QueryString(managementUrl.Query)
                                          {
                                              {"parentid", ParentNode.ID.ToString()}
                                          };
                    AddNodeButton.NavigateUrl = managementUrl.GetLeftPart(UriPartial.Path) +
                        queryString;
                    AddNodeButton.Enabled = true;
                }
                else
                {
                    AddNodeButton.Enabled = false;
                }
            }

            AddNodeButton.Text = Translator.Translate("Medianamik_Forum", translationKey);

            NoConfigurationMessage.Visible = !AddNodeButton.Enabled;

            AddNodeButton.CssClass = AddNodeButton.Enabled ? "Action BtAjouter" : "Action BtAjouter-Inactif";
        }

        private int GetForumConfigurationCount()
        {
            return new Query()
                .Where(n => n.ParentID, Comparison.Equal, RootNodeId)
                .Where(n => n.NodeTypeID, Comparison.Equal,
                    ForumTypes.ForumConfiguration)
                .Count();
        }

        #endregion
    }
}
